class PartSalsesController < ApplicationController
  before_action :set_menu

  def index
    @submenu = :part_salse
    @title = '配件零售单'
    @part_salses = PartSalse.all
  end

  def new
    @title = "配件零售单/新增"
    @buttons.push :action => part_salses_path, :label => "返回"
    if params.has_key? :car_mo_check
      @car_brand = CarBrand.find params[:customer][:car_brand_id]
      @car_model = CarModel.find params[:customer][:car_model_id]
    end
    if params.has_key? :check 
      @car_num = params[:n1]+params[:n2]+params[:n3]
      @customer = Customer.find_by_car_num @car_num
      if @customer.nil?
        @infos.push "没有客户记录"
      end
    end
    if params.has_key? :save
      @customer = Customer.find_by_car_num params[:car_num]
      if @customer.nil?
        @customer = Customer.create(customer_level_id: 1, name: params[:name], phone: params[:phone], car_num: params[:car_num], car_mo: params[:car_mo])
        @part_salse = PartSalse.create(customer_id: @customer.id, note: params[:note], user_id: current_user.id)
        redirect_to part_salse_path(:id=>@part_salse.id)
      else
        @part_salse = PartSalse.create(customer_id: @customer.id, note: params[:note], user_id: current_user.id)
        redirect_to part_salse_path(:id=>@part_salse.id)
      end
    end
  end


  def show
    @title = "配件零售单/明细"
    @buttons.push :action => part_salses_path, :label => "返回"
    @part_salse = PartSalse.find params[:id]
    if params.has_key? :save
      if @part_salse.part_salse_details.blank?
        @infos.push "请增加明细"
      else
        @part_salse.update_salse_status
        redirect_to part_salses_path
      end
    end
  end

  def destroy
    @part_salse = PartSalse.find params[:id]
    @part_salse.destroy
    redirect_to part_salses_path
  end


  private
  def set_menu
    @mainmenu = :part
  end
end
